(ns readerManager
    "This namespace contains functions that use the readbinfile namespace"
 (:import (java.io FileInputStream DataInputStream RandomAccessFile File)
          (java.nio ByteBuffer CharBuffer )
          (java.nio.channels FileChannel)
 )
 (:use readbinfile)
 )

(defn get-db-vector [file]
  "Returns a vector containing magic-number, offset ,num-fields ,fields-meta and records"
  (read-bin-file file)
)

(defn get-headers [file]
  "Returns the header's fields in the file database to use in a table"    
  ;(keys (first (get-records file)))
)

(defn get-numFields [file]
  "Return the number of fields in a file"
  (count ( read-bin-rec file))
)

(defn get-fields [file]
  "Returns the value of the fields in a file"
  (get file :fields)
)

(defn get-records [file]
  "Return the fields in a file db"
  (read-bin-rec file)
)

(defn erase
  "erases a row in a file by changing the :deleted flag"
    [file rowNumber]
    (with-open [fileMan (RandomAccessFile. file "rw")]
        (.readInt fileMan); read magic number
        (let [offset (.readInt fileMan)]
            (.seek fileMan (+ offset (* 161 rowNumber)))
            (.writeShort fileMan 0x8000)))
)

(defn new-values
"Creates a new register in the file with the specified values"
[file row name city size smoking price date owner]
  (let [
        nameB    (ByteBuffer/allocate 64)
        cityB    (ByteBuffer/allocate 64)
        sizeB    (ByteBuffer/allocate 4)
        smokingB (ByteBuffer/allocate 1)
        priceB   (ByteBuffer/allocate 8)
        dateB    (ByteBuffer/allocate 10)
        ownerB   (ByteBuffer/allocate 8)        
       ]
        (.put nameB    (.getBytes name "US-ASCII"))
        (.put cityB    (.getBytes city "US-ASCII"))
        (.put sizeB    (.getBytes size "US-ASCII"))
        (.put smokingB (.getBytes smoking "US-ASCII"))
        (.put priceB   (.getBytes price "US-ASCII"))
        (.put dateB   (.getBytes date "US-ASCII"))
        (.put ownerB   (.getBytes owner "US-ASCII"))

        (with-open [fileWR (RandomAccessFile. file "rw")]
          (.readInt fileWR); read magic number
          (let [offset (.readInt fileWR)]
          (.seek fileWR (+ offset (* 161 row)))
            (.writeShort fileWR 0)
            (.write fileWR (.array nameB))
            (.write fileWR (.array cityB))
            (.write fileWR (.array sizeB))
            (.write fileWR (.array smokingB))
            (.write fileWR (.array priceB))
            (.write fileWR (.array dateB))
            (.write fileWR (.array ownerB))
          )

   )
 )
)


;(pr( get-records "db-1x2.db"))
;(pr( get-numFields "db-1x2.db"))
;(pr (get-headers "db-1x2.db"))
;(pr (get-fields "db-1x2.db"))
;(pr (get-db-vector "db-1x2.db"))



